package com.lesama.thread;

/*
    开启线程的第三种方式：
        1. 编写一个类实现Callable接口
        2. 重写call方法
        3. 将线程任务代码写在call方法中
        4. 创建线程任务资源对象
        5. 创建线程任务对象，封装线程资源
        6. 创建线程对象，传入线程任务对象
        7. 使用线程对象调用start开启线程
 */

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();
        FutureTask<Integer> task1 = new FutureTask<>(mc);
        FutureTask<Integer> task2 = new FutureTask<>(mc);
        Thread thread1 = new Thread(task1);
        Thread thread2 = new Thread(task2);
        thread1.start();
        thread2.start();

        Integer sum1 = task1.get();
        Integer sum2 = task2.get();
        System.out.println("任务1执行的结果为：" + sum1);
        System.out.println("任务2执行的结果为：" + sum2);
    }
}

class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
            System.out.println("sum = " + sum);
        }
        return sum;
    }
}
